<%--
  Created by IntelliJ IDEA.
  User: honor
  Date: 2025/7/29
  Time: 11:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<!-- 使用国内CDN加速 -->
<script src="js/bootstrap.bundle.min.js"></script>
<!-- 在JSP页面的head或body底部添加 -->
<script src="${pageContext.request.contextPath}/js/notification.js?v=3"></script>


<script>
    // 假设从session或其他方式获取当前用户ID
    var currentUserId = '${sessionScope.user.id}';
    console.log('currentUserId:' +currentUserId)// 根据你的用户系统调整
    if (currentUserId) {
        NotificationManager.init(currentUserId);
    }
</script>
<html>
<head>

        <title>码农小站</title>
        <link rel="icon" href="./favicon/favicon.ico" type="image/x-icon">
    <!-- 使用国内CDN加速 -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.11.1/font/bootstrap-icons.min.css">
    <script src="js/jquery-2.0.2.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
    <style>
        .btn-active {
            background-color: #0d6efd !important;
            color: white !important;
        }

        .btn-favorite-active {
            background-color: #ffc107 !important;
            color: white !important;
        }

        .title {
            font-weight: bold;
            color: #333;
            text-decoration: none;
        }

        .author {
            font-weight: 500;
            color: #acacac; /* 默认灰色 */
            text-decoration: none;
            transition: color 0.3s; /* 平滑颜色变化 */
        }

        .author:hover {
            color: #000; /* 鼠标悬停时变黑 */
        }

        .content {
            display: -webkit-box;
            -webkit-line-clamp: 2; /* 显示两行 */
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .bi bi-envelope {
             background-size: cover;
            width: 24px; /* 根据需要调整大小 */
            height: 24px;
            display: inline-block;
            vertical-align: middle;
        }
        .btn-custom {
            background-color: white; /* 设置背景颜色为白色 */
            border-color: #6c757d; /* 设置边框颜色 */
            color: #212529; /* 设置文本颜色 */
        }

        .btn-custom:hover {
            background-color: #e9ecef; /* 设置悬停时的背景颜色 */
            border-color: #6c757d; /* 设置悬停时的边框颜色 */
            color: #212529; /* 设置悬停时的文本颜色 */
        }

    </style>
</head>
<body class="container mt-4">
<h2>码农小站</h2>
<nav class="nav nav-pills d-flex justify-content-between">
    <!-- 左侧内容 -->

    <!-- 右侧登录/注册 -->
    <div class="ms-auto">   <!-- 关键：ms-auto 把它推到最右边 -->
        <a href="${pageContext.request.contextPath}/messageServlet?method=findMessageByReceiveId" class="btn btn-info btn-custom d-inline-block ms-auto">
            <i class="bi bi-envelope"></i>
        </a>
        <c:choose>
            <c:when test="${empty sessionScope.user}">
                <a class="nav-link d-inline-block" href="${pageContext.request.contextPath}/login.jsp">登录</a>
                <a class="nav-link d-inline-block" href="${pageContext.request.contextPath}/register.jsp">注册</a>
            </c:when>
            <c:otherwise>
<%--                <span class="navbar-text me-2">欢迎，${sessionScope.user.username}</span>--%>
                <a class="nav-link d-inline-block" href="${pageContext.request.contextPath}/userServlet?method=findByLoginUserId&id=${sessionScope.user.id}">
                    欢迎，${sessionScope.user.username}
                </a>
                <a class="nav-link d-inline-block" href="${pageContext.request.contextPath}/loginServlet?method=logout">退出</a>

            </c:otherwise>
        </c:choose>
    </div>
</nav>


<!-- 一列一行 -->
<div class="row row-cols-1 g-3">
    <c:forEach items="${articleList}" var="article">
        <div class="col">
            <div class="card shadow-sm">
                <div class="card-body">


    <a href="articleServlet?method=findByTitle&id=${article.id}" class="title">${article.title}</a>
    <h6 class="card-subtitle mb-2 text-muted">
        作者：<a class="author" href="${pageContext.request.contextPath}/articleServlet?method=userProfile&userId=${article.userId}">${article.userName}</a> · ${article.createdAt}
    </h6>
    <p class="card-text content">${article.content}</p>


                </div>

                <div class="card-footer bg-white border-0">
                     <span>
            <!-- 点赞 -->
                <button class="btn btn-sm btn-outline-primary like-btn ${article.userLiked ? 'btn-active' : ''}" onclick="start(${article.id})"
                        data-id="${article.id}">
                <i class="bi bi-hand-thumbs-up"></i>
             <span class="like-count" id="startCount${article.id}">${article.startCount}</span>
            </button>

                         <!-- 收藏 -->
                <button class="btn btn-sm btn-outline-warning favorite-btn ms-2 ${article.userFavorited ? 'btn-favorite-active' : ''}" onclick="favorite(${article.id})"
                        data-id="${article.id}">
            <i class="bi bi-star"></i>
             <span class="favorite-count" id="favoriteCount${article.id}">${article.favoriteCount}</span>
            </button>
    </span>

                    <c:if test="${article.canDelete}">
                        <button class="btn btn-sm btn-danger"
                                onclick="deleteArticle(${article.id})">删除</button>
                    </c:if>

                    <c:if test="${article.canEdit}">
                        <button class="btn btn-sm btn-warning edit-btn"
                                data-id="${article.id}"
                                data-title="${fn:escapeXml(article.title)}"
                                data-content="${fn:escapeXml(article.content)}">
                            编辑
                        </button>


                    </c:if>


                </div>
            </div>
        </div>
    </c:forEach>
</div>

<a class="btn btn-primary mt-4" href="articleEdit.jsp">新增文章</a>


<!-- 编辑文章模态框 -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <form id="editForm" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑文章</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="id" id="editArticleId">
                <div class="mb-3">
                    <label class="form-label">标题</label>
                    <input type="text" class="form-control" name="title" id="editTitle" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">正文</label>
                    <textarea class="form-control" name="content" id="editContent" rows="5" required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>
</body>

<script>


    $(document).on('click', '.edit-btn', function () {
        const id = $(this).data('id');
        const title = $(this).data('title');
        const content = $(this).data('content');

        $('#editArticleId').val(id);
        $('#editTitle').val(title);
        $('#editContent').val(content);

        new bootstrap.Modal(document.getElementById('editModal')).show();
    });

    // 提交编辑表单
    $('#editForm').on('submit', function (e) {
        e.preventDefault();
        $.post('articleServlet?method=update', $(this).serialize())
            .done(function () {
                alert('更新成功');
                location.reload(); // 刷新页面
            })
            .fail(function () {
                alert('更新失败');
            });
    });


    function toggleAction(id, type) {
        $.post(`article/${type}/${id}`)
            .done(function (data) {
                // data: {"count":12,"active":true}
                const btn = $(`.${type}-btn[data-id=${id}]`);
                btn.find('span').text(data.count);
                btn.toggleClass('btn-outline-primary active', type === 'like');
                btn.toggleClass('btn-outline-warning active', type === 'favorite');
            });
    }
    function start(id) {
        $.post('articleServlet?method=start&id=' + id)
            .done(function (data) {
                let obj = JSON.parse(data);
                if (obj.error) {
                    alert(obj.error);
                    return;
                }

                // 更新点赞数
                $('#startCount' + id).text(obj.count);

                // 更新按钮样式
                let btn = $('.like-btn[data-id="' + id + '"]');
                if (obj.liked) {
                    btn.addClass('btn-active');
                } else {
                    btn.removeClass('btn-active');
                }
                btn.find('i').toggleClass('bi-hand-thumbs-up-fill', obj.liked);

            })
            .fail(function () {
                alert("请求失败");
            });
    }

    function favorite(id) {
        $.post('articleServlet?method=favorite&id=' + id)
            .done(function (data) {
                let obj = JSON.parse(data);
                if (obj.error) {
                    alert(obj.error);
                    return;
                }

                // 更新收藏数
                $('#favoriteCount' + id).text(obj.count);

                // 更新按钮样式
                let btn = $('.favorite-btn[data-id="' + id + '"]');
                if (obj.liked) {
                    btn.addClass('btn-favorite-active');
                } else {
                    btn.removeClass('btn-favorite-active');
                }
                btn.find('i').toggleClass('bi-star-fill', obj.liked);

            })
            .fail(function () {
                alert("请求失败");
            });
    }
    function deleteArticle(id) {
        if (confirm('确定删除这篇文章吗？')) {
            location.href = '${pageContext.request.contextPath}/articleServlet?method=delete&id=' + id;
        }
    }

</script>

</html>
